package com.wuda.servlet;

import com.wuda.bean.Book;
import com.wuda.dao.BorrowRecordDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/getTopBorrowedBooks")
public class GetTopBorrowedBooks extends HttpServlet {
	BorrowRecordDao borrowRecordDao = new BorrowRecordDao();

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws   IOException {
		resp.setContentType("application/json; charset=utf8");


		List<Book> topBorrowedBooks = borrowRecordDao.getTopBorrowedBooks();

		JSONArray jsonArray = new JSONArray();
		for (Book book : topBorrowedBooks) {
			JSONObject jsonData = new JSONObject();
			jsonData.put("bookId", book.getBookId());
			jsonData.put("title", book.getTitle());
			jsonData.put("author", book.getAuthor());
			jsonData.put("isbn", book.getIsbn());
			jsonData.put("publisher", book.getPublisher());
			jsonData.put("publishDate", book.getPublishDate().toString());
			jsonData.put("stockQuantity", book.getStockQuantity());
			jsonData.put("type", book.getType());
			jsonData.put("introduce", book.getIntroduce());
			jsonArray.add(jsonData);
		}

		JSONObject jsonResult = new JSONObject();
		jsonResult.put("code", 200);
		jsonResult.put("msg", "查询成功");
		jsonResult.put("data", jsonArray);

		try (PrintWriter out = resp.getWriter()) {
			out.print(jsonResult);
			out.flush();
		}
	}



}
